package com.sunshine.wheel.study.netty.chat.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.commons.lang3.StringUtils;
import org.msgpack.MessagePack;
import org.msgpack.MessageTypeException;

import java.util.List;

/**
 * 自定义消息的解码器
 */
public class IMDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        try{
            final int length = in.readableBytes();
            final byte[] array = new byte[length];
            String content = new String(array, in.readerIndex(), length);

            // 不解析空消息
            if (StringUtils.isNotBlank(content)) {
                if (!IMPEnum.isIMP(content)) {
                    ctx.channel().pipeline().remove(this);
                    return;
                }
            }

            in.getBytes(in.readerIndex(), array, 0, length);
            out.add(new MessagePack().read(array,IMMessage.class));
            in.clear();
        }catch(MessageTypeException e){
            ctx.channel().pipeline().remove(this);
        }
    }
}
